WEBAPP['gameBauCua'] = function() {
	$.each(HooHey.init, function(key, func) {
		func();
	});

};

var HooHey = {};
HooHey.init = {
	price : function() {
		$('#prices').find('.price input').on('click touch', function(e) {
			$('#selPrice').removeAttr('id');

			var price = $(this).parent().attr('id', 'selPrice').end().val();
			price = parseInt(price, 10);

			HooHey.onChoicePrice(price);

			// clear
			price = null;
		}).tooltip({
			placement : 'auto'
		}).get(4).click();
	},

	door : function() {
		$('#doors').find('.door').on('click touch', function() {
			var id = parseInt($(this).attr('door'), 10);
			HooHey.Doors.choose(id);
			return false;
		});
	},

	dice : function() {
		$.fn.setDice = function(val) {
			return this.each(function() {
				var T = $(this);
				T.removeClass(T.attr('cur')).addClass(val).attr('cur', val);
			});
		};

		for (var i = 0; i < 3; i++) {
			HooHey.Dices.dices[i] = $('#dice' + i);
		}

		HooHey.Dices.show();
	},

	start : function() {
		$('#startButton').on('click touch', function() {
			HooHey.Board.start();
		});
		HooHey.Board.showStart();
	}
};

HooHey.Util = {
	numberWithCommas : function(x) {
		return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
	}
};

HooHey.choicePrice = 0;
HooHey.onChoicePrice = function(price) {
	HooHey.choicePrice = price;
};

HooHey.Doors = {
	watchCount : 0,
	totalDoors : 0,
	doors : [ 0, 0, 0, 0, 0, 0 ],

	choose : function(id) {
		if (HooHey.State.state === 'bet') {
			if (HooHey.Board.balance >= HooHey.choicePrice) {
				HooHey.Doors.doors[id] += HooHey.choicePrice;

				HooHey.Doors.totalDoors += HooHey.choicePrice;
				HooHey.Doors.watchCount = 0;

				HooHey.Board.changeBalance(-HooHey.choicePrice);
				$('#door' + id).find('.bet').text(HooHey.Util.numberWithCommas(HooHey.Doors.doors[id]) + ' xu');
			} else {
				console.log('hết xu');
			}
		}
//		else if (HooHey.State.state === 'wait') {
//			HooHey.Board.start();
//
//			// clear timer đợi start bàn mới nếu có
//			HooHey.State.clearWait();
//		}
	}
};

HooHey.Dices = {
	show : function() {
		$('#hostBoard').find('.host-control').hide();
		$('#dices').show();
	},

	dices : [ null, null, null ],
	rollTime : 0,
	rollCount : 0,
	rolls : function() {
		HooHey.Dices.rollTime = $.now() + HooHey.Board.timeRoll * 1000;

		for (var i = 0; i < HooHey.Dices.dices.length; i++) {
			HooHey.Dices.roll(HooHey.Dices.dices[i]);
		}
		HooHey.Dices.rollCount = HooHey.Dices.dices.length;
	},

	genDice : function() {
		return 'dice-' + Math.floor(Math.random() * 6);
	},
	genTime : function() {
		return 300 + Math.floor(Math.random() * 600);
	},

	roll : function(dice) {
		var tmp = 0;
		dice.setDice(HooHey.Dices.genDice()).animate({
			backgroundPositionY : 50
		}, HooHey.Dices.genTime(), 'linear', function() {
			$(this).setDice(HooHey.Dices.genDice()).animate({
				backgroundPositionY : -50
			}, HooHey.Dices.genTime(), 'linear', function() {
				var T = $(this);

				// roll đủ thời gian tối thiểu và có kết quả thì dừng dice này
				if ($.now() > HooHey.Dices.rollTime && HooHey.State.state === 'result') {
					HooHey.Dices.rollFinish(T);
				} else {
					HooHey.Dices.roll(T);
				}
				// clear
				T = null;
			})
		});
	},

	rollFinish : function(dice) {
		HooHey.Dices.rollCount--;
		dice.setDice('dice-' + HooHey.Board.result.dices[dice.attr('dice')]).animate({
			backgroundPositionY : 0
		});
		if (HooHey.Dices.rollCount === 0) {
			HooHey.Board.showResult();
		}
	}
};

HooHey.Progress = {
	timeSpent : 0,
	show : function() {
		$('#hostBoard').find('.host-control').hide();
		$('#progress').show();
	},

	timer : null,
	bar : $('#progressBar'),
	start : function() {
		HooHey.Progress.bar.width('1%');
		HooHey.Progress.show();

		HooHey.Progress.timeSpent = 0;
		if (HooHey.Progress.timer != null) {
			clearInterval(HooHey.Progress.timer);
		}

		HooHey.Progress.timer = setInterval(function() {
			HooHey.Progress.timeSpent++;

			if (HooHey.Progress.timeSpent > HooHey.Board.timeBet) {
				clearInterval(HooHey.Progress.timer);
				HooHey.Board.commit();
			}

			var percent = (HooHey.Progress.timeSpent / HooHey.Board.timeBet) * 100;
			HooHey.Progress.bar.width(percent + '%');
		}, 1000);
	}
};

HooHey.State = {
	state : 'wait',

	goBet : function() {
		HooHey.State.state = 'bet';
		$('#doors').addClass('bet-ok').find('.bet').text('');
	},

	goCommit : function() {
		HooHey.State.state = 'commit';
		$('#doors').removeClass('bet-ok');

		HooHey.Dices.show();
		HooHey.Dices.rolls();
	},

	goResult : function() {
		HooHey.State.state = 'result';
	},

	waitTimer : null,
	goWait : function() {
		HooHey.State.state = 'wait';
		// start new game
		HooHey.State.waitTimer = setTimeout(HooHey.Board.start, 10000);
	},
	clearWait : function() {
		if (HooHey.State.waitTimer != null) {
			clearTimeout(HooHey.State.waitTimer);
		}
	}

};

HooHey.Board = {
	result : null,
	token : null,
	timeBet : 0,
	timeRoll : 0,
	watchCountLimit : 0,

	showStart : function() {
		$('#hostBoard').find('.host-control').hide();
		$('#startButtonCon').show();
	},

	balance : 0,
	balObj : $('#balance'),
	updateBalance : function(bal) {
		if (bal != HooHey.Board.balance) {
			var val1 = HooHey.Board.balance;
			HooHey.Board.balance = bal;

			HooHey.Board.aniBalance(val1, HooHey.Board.balance);
		}
	},
	changeBalance : function(val) {
		HooHey.Board.updateBalance(HooHey.Board.balance + val);
	},
	aniBalance : function(val1, val2) {
		$({
			someValue : val1
		}).animate({
			someValue : val2
		}, {
			duration : 500,
			easing : 'swing', // can be anything
			step : function() { // called on every step
				HooHey.Board.balObj.text(HooHey.Util.numberWithCommas(Math.round(this.someValue)) + ' xu');
			},
			done : function() {
				HooHey.Board.balObj.text(HooHey.Util.numberWithCommas(val2) + ' xu');
			}
		});
	},

	start : function() {
		// reset doors
		for (var i = 0; i < 6;) {
			HooHey.Doors.doors[i++] = 0;
		}
		HooHey.Doors.totalDoors = 0;

		HooHey.Board.requestGame();
	},

	requestGame : function() {
		$.post('/json/baucua/req', {}, function(data) {
			HooHey.Board.updateBalance(data.balance);
			HooHey.Board.token = data.token;
			HooHey.Board.timeBet = data.timeBet;
			HooHey.Board.timeRoll = data.timeRoll;
			HooHey.Board.watchCountLimit = data.watchCountLimit;

			HooHey.State.goBet();
			HooHey.Progress.start();
		});
	},

	commit : function() {
		HooHey.State.goCommit();

		$.post('/json/baucua/commit', {
			token : HooHey.Board.token,
			doors : HooHey.Doors.totalDoors ? HooHey.Doors.doors.join(',') : null
		}, function(data) {
			HooHey.State.goResult();
			HooHey.Board.result = data;
		});

		if (HooHey.Doors.totalDoors === 0) {
			HooHey.Doors.watchCount++;
		}

	},

	showResult : function() {
		// show result
		HooHey.Board.updateBalance(HooHey.Board.result.balance);

		$.each(HooHey.Board.result.doors, function(i, val) {
			if (val > 0) {
				$('#door' + i).find('.bet').text('+' + HooHey.Util.numberWithCommas(val) + ' xu');
			}
		});

		if (HooHey.Doors.watchCount > 3) {
			HooHey.Board.showStart();
		} else {
			HooHey.State.goWait();
		}
	}
};